//
//  Dictionary+.swift
//  HoneyChat
//
//  Created by hccc on 2023/3/6.
//

import Foundation
extension Dictionary where Value: Optionalable {
    func filterNil() -> [Key: Value.Wrapped] {
        var newDictionary: [Key: Value.Wrapped] = [:]
        for (key, value) in self {
            guard let value = value.wrapped else { continue }
            newDictionary[key] = value
        }
        return newDictionary
    }
}

extension Dictionary {
    var jsonString: String {
        let errorJson = "JSON Format error"
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
            return String(bytes: jsonData, encoding: String.Encoding.utf8)?.replacingOccurrences(of: "\\", with: "") ?? errorJson
        } catch {
            return errorJson
        }
    }
}

extension String {
    var json: [String: Any]? {
        do {
            guard let data = data(using: .utf8) else { return nil }
            let jsonData = try JSONSerialization.jsonObject(with: data)
            return jsonData as? [String: Any]
        } catch {
            return nil
        }
    }
}
